from typing import *


class Solution:
    def maxFrequency(self, nums: List[int], k: int, numOperations: int) -> int:
        cnt = Counter(nums)
        keys = sorted(cnt.keys())
        l, r, tot = 0, 0, 0
        ans = 0
        for v in range(min(keys), max(keys) + 1):
            lv, rv = v - k, v + k
            while r < len(keys) and keys[r] <= rv:
                tot += cnt[keys[r]]
                r += 1
            while l < len(keys) and keys[l] < lv:
                tot -= cnt[keys[l]]
                l += 1
            if v in cnt.keys():
                ans = max(ans, cnt[v] + min(tot - cnt[v], numOperations))
            else:
                ans = max(ans, min(tot, numOperations))
        return ans
